﻿using Kinlo.Entitys;
using MaterialDesignThemes.Wpf;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using UIWindows.Commands;
using UIWindows.Domains;
using UIWindows.GlobalStatics;
using UIWindows.Models.ParameterModels;
using UIWindows.Tools.Helper;
using UIWindows.Views.DeviceInteractiveaddressItems;
using XingLucifer.IBase.Enums;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace UIWindows.ViewModels.DeviceInteractiveaddressItems
{
    public class CollectParameterViewModel : ViewModelBase
    {
        GlobalStatics.DeviceInteractiveaddressStatic _parameterStatic;
        public UserConfigStatic UserConfig { get; set; }
        public string SearchText { get; set; } = string.Empty;
        /// <summary>
        /// 界面展示
        /// </summary>
        public ObservableCollection<CollectParameterModel> CollectParameter { get; set; } = new ObservableCollection<CollectParameterModel>();
        /// <summary>
        /// 取的原始集合
        /// </summary>
        public ObservableCollection<PropertyDto> BatteryPropertys { get; set; } = new ObservableCollection<PropertyDto>();
        /// <summary>
        /// 搜索后保留集合
        /// </summary>
        public ObservableCollection<PropertyDto> SearchBatteryPropertys { get; set; } = new ObservableCollection<PropertyDto>();

        public SystemConfigStatic _configStatic { get; set; }
        public CollectParameterViewModel(GlobalStatics.DeviceInteractiveaddressStatic parameter, UserConfigStatic userConfig, SystemConfigStatic systemConfigStatic)
        {
            _parameterStatic = parameter;
            UserConfig = userConfig;
            _configStatic=systemConfigStatic;
            MachineInfoList.AddRange(Enum.GetValues(typeof(MachineInfoTypes)).Cast<object>());
            MachineInfoValue = MachineInfoTypes.卷芯上料;

            //if (_configStatic.SCM.MainDeviceType == MainDeviceTypeEnum.前段组装线)
            //{
            //    MachineInfoList = new List<object>
            //    {
            //        MachineInfoTypes.入壳机,
            //        MachineInfoTypes.点底焊,
            //        MachineInfoTypes.辊槽机,
            //    };
            //    MachineInfoValue = MachineInfoTypes.入壳机;
            //}
        }

        void PropertiesLoad(MachineInfoTypes machineInfoValue)
        {
            //switch (machineInfoValue)
            //{
            //    case MachineInfoTypes.卷芯上料:
            //        AddProperties(typeof(CoilCoreLoadingData));
            //        break;
            //    case MachineInfoTypes.入壳机:
            //        AddProperties(typeof(ShellInsertionData));
            //        break;
            //    case MachineInfoTypes.折极耳:
            //        AddProperties(typeof(PoleEarFoldingData));
            //        break;
            //}

            switch (machineInfoValue)
            {
                case MachineInfoTypes.卷芯上料:
                    AddProperties(typeof(CoilCoreLoadingData));
                    break;
                case MachineInfoTypes.换套杯:
                    AddProperties(typeof(CupSleeveChangingData));
                    break;
                case MachineInfoTypes.折极耳:
                    AddProperties(typeof(PoleEarFoldingData));
                    break;
                case MachineInfoTypes.入壳机:
                    AddProperties(typeof(ShellInsertionData));
                    break;
                case MachineInfoTypes.点底焊:
                    AddProperties(typeof(SpotoWeldData));
                    break;
                case MachineInfoTypes.辊槽机:
                    AddProperties(typeof(GrooveRollingMachineData));
                    break;
                case MachineInfoTypes.短路测试仪:
                    AddProperties(typeof(ShortCircuitTesterData));
                    break;
                case MachineInfoTypes.装盘机:
                    AddProperties(typeof(TrayFillerData));
                    break;
                case MachineInfoTypes.拆盘机:
                    AddProperties(typeof(DismantlingDiscData));
                    break;
                case MachineInfoTypes.盖帽焊:
                    AddProperties(typeof(CapWeldingData));
                    break;
                case MachineInfoTypes.封口机:
                    AddProperties(typeof(SealingMachineData));
                    break;
                case MachineInfoTypes.清洗机:
                    AddProperties(typeof(CleaningData));
                    break;
                case MachineInfoTypes.套膜机:
                    AddProperties(typeof(MantleData));
                    break;
                case MachineInfoTypes.喷码机:
                    AddProperties(typeof(MarkingData));
                    break;
                case MachineInfoTypes.预充装盘:
                    AddProperties(typeof(Plate));
                    break;
                default: break;
            }
        }
        Type DataType { get; set; }
        void AddProperties(Type type)
        {
            BatteryPropertys.Clear();
            SearchBatteryPropertys.Clear();
            DataType =type;
            foreach (var item in type.GetProperties())
            {
                var attributes = item.GetCustomAttributes(true).OfType<DescriptionAttribute>().FirstOrDefault();
                if (attributes != null)
                {
                    BatteryPropertys.Add(new PropertyDto { Description = attributes.Description, PropertyName = item.Name });
                    SearchBatteryPropertys.Add(new PropertyDto { Description = attributes.Description, PropertyName = item.Name });
                }
            }
        }

        private MachineInfoTypes _machineInfoValue;

        public MachineInfoTypes MachineInfoValue
        {
            get { return _machineInfoValue; }
            set
            {
                if (_machineInfoValue != value) ;
                if (_parameterStatic.CollectParameters.ContainsKey(value))
                {
                    // 字典中已经存在指定键，获取对应的值
                    CollectParameter = _parameterStatic.CollectParameters[value];
                    // 在这里处理 existingCollection，例如添加、修改或获取它的值
                }
                else
                {
                    // 字典中不存在指定键，需要添加键值对
                    CollectParameter = new ObservableCollection<CollectParameterModel>();
                }
                PropertiesLoad(value);
                _machineInfoValue = value;
                OnPropertyChanged(nameof(MachineInfoValue));
            }
        }

        /// <summary>
        /// 设备列表
        /// </summary>
        public List<object> MachineInfoList { get; set; } = new List<object>();

        public DelegateCommand<string> SendSearchTextCMD => new DelegateCommand<string>(str =>
        {
            SearchText = str;
        });
        public DelegateCommand ExportCMD => new DelegateCommand(() =>
        {

        });
        public DelegateCommand ImportCMD => new DelegateCommand(() =>
        {
            try
            {
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Multiselect = false;//该值确定是否可以选择多个文件
                dialog.Title = "请选择文件";
                dialog.Filter = "Excel 工作簿(*.xls)|*.xls";
                var v = dialog.ShowDialog();
                if (v == true)
                {
                    string filePath = dialog.FileName;
                    var excelResult = ExportHelper.ImproExcel<CollectParameterModel>(filePath);
                    excelResult.ToList().ForEach(x =>
                    {
                        x.ID = CollectParameter.Count + 1;
                        CollectParameter.Add(x);
                    });
                }
            }
            catch (Exception)
            {


            }

        });
        /// <summary>
        /// 对比本地属性，如果对不上就清空
        /// </summary>
        public DelegateCommand ContrastCMD => new DelegateCommand(async () =>
        {
            var batteryPropertys = DataType.GetProperties();
            List<string> errMegs = new List<string>();
            foreach (var item in CollectParameter)
            {
                if (!batteryPropertys.Any(x => x.Name == item.PropertyName))
                {
                    errMegs.Add(item.Description);
                    item.PropertyName = string.Empty;
                    item.Description = string.Empty;
                }
            }
            if (errMegs.Count > 0)
            {
                await $"注意：{string.Join(",", errMegs)} 本地无此属性，已清空属性及特性列，请删除或重新选择！".MessageDialogs(MessageLevelType.警告, true, Enums.PopUpTypes.Global, Visibility.Visible);

            }
            else
            {
                MyMessageQueue.Enqueue("所有属性对比无错！", "知道啦", () => { });
            }
        });

        public DelegateCommand CreateCMD => new DelegateCommand(() =>
        {
            CollectParameter.Add(new CollectParameterModel
            {
                ID = CollectParameter.Count + 1
            });
        });
        public DelegateCommand<DataGrid> RemoveCMD => new DelegateCommand<DataGrid>(data =>
        {
            try
            {
                int count = data.SelectedItems.Count;
                for (int i = count - 1; i > -1; i--)
                {
                    var ret = data.SelectedItems[i] as CollectParameterModel;
                    if (ret == null) { continue; }
                    var r = CollectParameter.FirstOrDefault(x => x.ID == ret.ID);
                    if (r != null)
                    {
                        CollectParameter.Remove(r);
                        for (int y = 0; y < CollectParameter.Count; y++)
                        {
                            CollectParameter[y].ID = y + 1;
                        }
                    }
                }

            }
            catch (Exception)
            {


            }

        });
        public SnackbarMessageQueue MyMessageQueue { get; set; } = new SnackbarMessageQueue(new TimeSpan(0, 0, 3));
        public DelegateCommand SaveCMD => new DelegateCommand(async () =>
        {
            //if (CollectParameter.Any(x => string.IsNullOrEmpty(x.PropertyName)))
            //{
            //    MyMessageQueue.Enqueue("本地属性不能有空！", "知道啦", () => { });
            //    return;
            //}

            var bl = (string)await "确定修改？".MessageDialogs(MessageLevelType.警告, true, Enums.PopUpTypes.Global, Visibility.Visible);
            if (bl == "true")
            {
                _parameterStatic.CollectParameters[MachineInfoValue] = new ObservableCollection<CollectParameterModel>(ConversionHelper.CopyList(CollectParameter));
                _parameterStatic.Save();
                $"用户：[{UserConfig.LoginUser.Name}] 修改成功！".OperationLog(MessageLevelType.成功);
                MyMessageQueue.Enqueue("修改成功！", "知道啦", () => { });
            }


        });

        public DelegateCommand SearchCMD => new DelegateCommand(() =>
        {
            SearchBatteryPropertys = new ObservableCollection<PropertyDto>(BatteryPropertys.Where(x => x.Description.Contains(SearchText)));
        });

        public DelegateCommand<List<object>> SelectTextCMD => new DelegateCommand<List<object>>(arr =>
        {
            if (arr != null && arr.Count >= 2)
            {
                PropertyDto str = arr[0] as PropertyDto;
                CollectParameterModel collectParameterModel = arr[1] as CollectParameterModel;
                collectParameterModel.Description = str.Description;
                collectParameterModel.PropertyName = str.PropertyName;
            }
        });
    }

}
